/*
 * @Description: 登记（新增条目）弹窗
 * @Author: Rfan
 * @Date: 2022-06-17 19:46:09
 * @LastEditTime: 2023-01-06 19:19:07
 */

import { useEffect, useState } from 'react';
import { Button, Form, Modal } from 'antd';
import { LeggoForm } from '@/components/form-builder';
import { fetchDescCardForm, genSerialNum, IGenSerialNumProps } from '@/api/archives/archives';
import { fetchDicItemListById } from '@/api/rulesettings/dictionary';
import { isNullObj, jsonClone } from '@/utils';
import type { FC } from 'react';
import type { ICoordinate } from '@/interfaces/global';
import { debounce } from 'lodash-es';
import { useLibraryCollectionContext } from '../../contexts/LibraryCollectionContext';
import { EnumInitRepoName } from '@/view/system/LIBManage/dictionaries';

const SAVE_TYPE = {
  CANCEL: 1,
  SAVE: 2
};

interface AddLibraryItemDialog {
  coordinate: ICoordinate;
  onSave: any;
}

const dbName = EnumInitRepoName.Collection;

const AddLibraryItem: FC<AddLibraryItemDialog> = (props) => {
  const { coordinate, onSave } = props;
  const { recordsData, addCollectItemFunc } = useLibraryCollectionContext();
  const [form] = Form.useForm();
  const leggo = LeggoForm.useLeggo();

  // 弹窗展示状态
  const [visible, setVisible] = useState(false);
  // 元数据及其规则列表
  const [propertyList, setPropertyList] = useState([]);
  // 分组规则，排序规则，序号规则
  const [groupSortRule, setGroupSortRule] = useState(null);

  useEffect(() => {
    if (visible) {
      fetchDescCardForm(coordinate).then((res) => {
        const { cardPropertyList, descCardFormJson, groupSortRule } = res.data;
        const schemaModel = JSON.parse(descCardFormJson);
        // 渲染表单
        leggo.resetSchemaModel(schemaModel);
        setPropertyList(cardPropertyList);
        setGroupSortRule(groupSortRule);
        // 新增弹窗序号禁止填写
        leggo.updateSchema('arccode', (configs) => {
          const { inputProps } = configs;
          inputProps.disabled = true;
        });
      });
    }
  }, [visible]);

  useEffect(() => {
    if (propertyList.length > 0) {
      propertyList.forEach((item) => {
        const { field } = item;
        // 处理关联字典表的情况
        if (field.dict_type_id > 0) {
          // 根据字典id获取字典列表
          fetchDicItemListById(field.dict_type_id).then((res) => {
            const { data } = res;
            console.log('dic item ', data);
            leggo.updateSchema(field.field_name, (configs) => {
              const { inputProps } = configs;
              inputProps.options = data.map((item: any) => {
                return { label: item.name, value: `${item.name}:${item.code}:${item.value}` };
              });
            });
          });
        }
      });
    }
  }, [propertyList]);

  useEffect(() => {
    if (groupSortRule && !isNullObj(groupSortRule)) {
      const { groupFieldResultList, sortFieldResultList } = groupSortRule;
      // 对分组字段添onChange事件加请求序号
      groupFieldResultList &&
        groupFieldResultList.forEach((item: any) => {
          leggo.updateSchema(item.fieldName, (configs) => {
            const { inputProps } = configs;
            inputProps.onChange = debounce(() => {
              getOrderNo();
            }, 300);
          });
        });

      // 对排序字段添onChange事件加请求序号
      sortFieldResultList &&
        sortFieldResultList.forEach((item: any) => {
          console.log('field_name', item.fieldName);
          leggo.updateSchema(item.fieldName, (configs) => {
            const { inputProps } = configs;
            inputProps.onChange = debounce(() => {
              getOrderNo();
            }, 300);
          });
        });
    }
  }, [groupSortRule]);

  /**
   * @description: 序号相关字段填写完成后查询序号 如果没有相关需求则去掉
   */
  const getOrderNo = () => {
    // 表单数据
    const formData = form.getFieldsValue();
    // 分组字段，排序字段
    const { groupFieldResultList, sortFieldResultList } = groupSortRule;
    // 将分组字段与排序字段合并并去重
    const groupList = groupFieldResultList || [];
    const sortList = sortFieldResultList || [];
    const orgArr = [...groupList, ...sortList];
    const fieldArr = orgArr.filter((item: any, index: number) => {
      return orgArr.findIndex((field) => field.fieldId === item.fieldId) === index;
    });
    // 判断相关字段是否都填写
    const finishFlag = fieldArr.every((field) => formData[field.fieldName]);

    console.log('finish', finishFlag);

    if (finishFlag) {
      // TODO: 分组与排序具体字段值类型需要确认
      const groupFieldList = groupList.map((field: any) => ({
        fieldName: field.fieldName,
        fieldValue: formData[field.fieldName]
      }));

      const sortFieldList = sortList.map((field: any) => ({
        fieldName: field.fieldName,
        fieldValue: formData[field.fieldName]
      }));

      const params: IGenSerialNumProps = {
        atCode: recordsData.atCode,
        atType: recordsData.atType,
        level: recordsData.level,
        commonParams: { dbName },
        groupFieldList,
        sortFieldList,
        upLevelId: undefined
      };

      //  请求序号接口
      genSerialNum(params).then((res) => {
        const { data } = res;
        form.setFieldValue('arccode', data);
      });
    }
  };

  /**
   * @description: 根据字段名称查找元数据及规则
   * @param {string} fieldName 字段名
   * @return {*}
   */
  const getPropertyItem = (fieldName: string) => {
    return propertyList.find((item) => item.field?.field_name === fieldName) || {};
  };

  /**
   * @description: 根据规则拼接传入字段的值
   * @param {string} fieldName
   * @return {*}
   */
  const generateFieldVal = (fieldName: string) => {
    console.log('generateFieldVal', fieldName);
    const { relationRule } = getPropertyItem(fieldName);
    if (relationRule) {
      console.log({ relationRule });
      const { dependRelationRule, relationType } = relationRule;
      if (relationType === 1) {
        // 使用 dependRelationRule 规则
        if (dependRelationRule.length > 0) {
          const str: string = dependRelationRule
            .map((rule: any) => {
              if (rule.type === 1) {
                const _fieldName = rule.fieldValue.field_name;
                let _val = form.getFieldValue(_fieldName);
                const ruleFieldItem = getPropertyItem(_fieldName);
                console.log({ ruleFieldItem });

                if (ruleFieldItem?.field?.dict_type_id > 0 && _val) {
                  [, _val] = _val.split(':');
                }
                return _val;
              }
              return rule.strValue;
            })
            .join('');
          form.setFieldsValue({ [fieldName]: str });
        }
      } else {
        // 使用 inheritRelationRule 规则
        // 理论用不上
      }
    }
  };

  const onValuesChange = (changedValues: any) => {
    const _key = Object.keys(changedValues)[0];
    const { linkageTargetFiledList } = getPropertyItem(_key);
    if (linkageTargetFiledList?.length > 0) {
      linkageTargetFiledList.forEach((item: any) => {
        if (item.level === coordinate.level) {
          generateFieldVal(item.field_name);
        }
      });
    }
  };

  // 提交表单
  const submitFunc = () => {
    form.submit();
  };

  // 新增档案类型
  const onFinish = (vals: any) => {
    const entries = Object.entries(vals).map(([k, v]: [string, any]) => {
      return {
        fieldName: k,
        fieldValue: v
      };
    });
    // 额外必传字段，用于关联各个层级
    entries.push({
      fieldName: 'up_level_id',
      fieldValue: '' // 上级的row_id，如为顶级，则为空
    });

    const params = jsonClone(coordinate);
    params.entries = entries;
    params.commonParams = {
      dbName
    };

    addCollectItemFunc(params).then(() => {
      onCancel();
    });
  };

  const onCancel = (type: number = SAVE_TYPE.CANCEL, data?: any) => {
    if (type === SAVE_TYPE.SAVE) {
      onSave(data);
    }
    setVisible(false);
  };

  return (
    <>
      <Button
        type="primary"
        onClick={() => {
          setVisible(true);
        }}
      >
        新增
      </Button>
      <Modal
        destroyOnClose
        title="增加"
        visible={visible}
        width={1000}
        onCancel={() => {
          onCancel();
        }}
        footer={[
          <Button
            key="back"
            onClick={() => {
              onCancel();
            }}
          >
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={submitFunc}>
            确定
          </Button>
        ]}
      >
        <LeggoForm
          leggo={leggo}
          form={form}
          preserve={false}
          onValuesChange={onValuesChange}
          onFinish={onFinish}
        />
      </Modal>
    </>
  );
};

export default AddLibraryItem;
